<template>
  <div>
    <NavBar>
      <template #title>搜索</template>
    </NavBar>
    <van-search
    v-model="val"
      show-action
      placeholder="请输入搜索关键词"
      @search="onSearch"
      v-focus
    >
      <template #action>
        <div @click="onSearch">搜索</div>
      </template>
    </van-search>
    <div class="search-content">
      <div class="content">
        <span>最近搜索</span>
        <van-icon @click="remove" name="delete-o" size="14px"/>
      </div>
      <van-grid :column-num="3">
        <van-grid-item v-for="(item,index) in searchwords" :key="index">
          <button @click="goahead(item)">{{ item }}</button>
        </van-grid-item>
      </van-grid>
    </div>
  </div>
</template>

<script>
import { setSearchList, getSearchList, removeSearchList } from '@/utils/storage'
export default {
  directives: {
    focus: {
      inserted (el) {
        el.querySelector('input').focus()
      }
    }
  },
  name: 'SearchIndex',
  data () {
    return {
      searchwords: getSearchList() ? JSON.parse(getSearchList()) : ['手机', '电脑', '面包', '辣条'],
      val: ''
    }
  },
  methods: {
    onSearch (val) {
      if (this.searchwords.find(e => e === val)) {
        this.goahead(val)
      } else {
        this.searchwords.unshift(val)
        setSearchList(this.searchwords)
        this.$router.push(`/searchlist?search=${val}`)
      }

      this.val = ''
    },
    goahead (item) {
      const i = this.searchwords.findIndex(e => e === item)
      this.searchwords.splice(i, 1)
      this.searchwords.unshift(item)
      setSearchList(this.searchwords)
      this.$router.push(`/searchlist?search=${item}`)
    },
    remove () {
      // removeSearchList()
      removeSearchList()
      this.searchwords = getSearchList() ? JSON.parse(getSearchList()) : ['手机', '电脑', '面包', '辣条']
    }
  }
}
</script>

<style scoped>
.search{
  color: red;
}
.search-content{
  width: 100%;
  min-height: 100vh;
  background-color: rgb(247,247,247);
}
.search-content .content{
  font-size: 16px;
  color: rgb(123, 123, 123);
  display: flex;
  justify-content: space-between;
}
.search-content button{
  width: 100px;
  height: 30px;
  border: 1px solid rgb(201, 196, 196);
  border-radius: 15px;
  font-size: 16px;
  background-color: white;
}
::v-deep(.van-grid-item__content){
  background-color: rgb(247,247,247);
}

</style>
